'''
文件 模式 r(读) w(写) x(创建新的，有则报错) 更多参考：https://www.runoob.com/python3/python3-file-methods.html
异常
try except finally:
try with 可以不用写finally关闭流
'''
import time

# try except finally 读取文件
def read_file01():
    f = None
    try:
        f = open('D:/creditCode.txt', 'r', encoding='utf-8')
        print(f.read())
    except FileNotFoundError :
        print('文件不存在')
    except LookupError :
        print('编码格式不正确')
    except UnicodeEncodeError :
        print('解码错误')
    finally:
        if f:
            f.close()

# try with 读取文件
def read_file02():
    with open('D:/creditCode.txt', 'r', encoding='utf-8') as f:
        print(f.read())

    # 通过for-in循环逐行读取
    with open('D:/creditCode.txt', mode='r') as f:
        for line in f:
            print(line, end='')
            time.sleep(0.5)
    print()

    # 读取文件按行读取到列表中
    with open('D:/creditCode.txt') as f:
        lines = f.readlines()
    print(lines)

# 图片复制
def copy_image():
    try:
        with open('D:/微信图片_20230605145841.jpg', 'rb') as f1:
            data = f1.read()
            print(type(data))
        with open('D:/20230605145841_copy.jpg', 'wb') as f2:
            f2.write(data)
    except FileNotFoundError as e:
        print('文件找不到错误：')
    except IOError as e:
        print('IO错误：')
    print('执行结束')
        

if __name__ == '__main__':
    #read_file01()   
    # read_file02()         
    copy_image()